<template>
  <div class="ComposeMaterial">
    <!-- 顶部内容 -->
 

    <!-- 头部的搜索栏 -->
    <div class="serch_title">
      <div class="serch_left">
        <div class="serch_item">
          <span class="left_prefix">所属项目</span>
          <a-select
            placeholder="请选择项目"
            allow-clear
            class="input_self"
            ref="select"
            v-model:value="state.merchant_library_id"
            @focus="focus"
            @change="onSelectLibrary"
            style="width: 150px"
          >
            <a-select-option v-for="i in state.itemList" :value="i.id">{{
              i.name
            }}</a-select-option>
          </a-select>
        </div>

        <div class="serch_item" v-show="state.merchant_library_id">
          <!-- <span class="left_prefix">所属文件夹</span> -->
          <a-select
            :disabled="!state.merchant_library_id"
            style="width: 200px"
            v-model:value="state.folder_id"
            :filter-option="false"
            allowClear
            @change="serchChange"
            placeholder="请选择文件夹"
            :options="state.folderList"
          >
            <template v-if="fetching" #notFoundContent>
              <a-spin size="small" />
            </template>
          </a-select>
        </div>

        <div class="serch_item">
          <!-- <span class="left_prefix">视频名称</span> -->
          <a-input
            allow-clear
            @change="(e) => e.type == 'click' && getMediaList()"
            style="width: 200px"
            v-model:value="state.material_name"
            placeholder="请输入视频名称"
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input>
        </div>

        <div class="serch_item">
          <!-- <span class="left_prefix">日期筛选</span> -->
          <!-- 日期  -->
          <a-range-picker
            @change="timeChange"
            format="YYYY-MM-DD"
            v-model:value="state.time"
            show-time
          />
        </div>
        <div class="serch_item">
          <span class="left_prefix">发布状态</span>
          <a-select
            placeholder="请选择发布状态"
            allow-clear
            class="input_self"
            v-model:value="state.useRelease"
            style="width: 150px"
          >
            <a-select-option value="all">全部</a-select-option>
            <a-select-option :value="1">已发布</a-select-option>
            <a-select-option :value="2">未发布</a-select-option>
          </a-select>
        </div>

        <div class="serch_item" v-if="state.useRelease == 1 || state.useRelease == 2">
          <span class="left_prefix">平台选择</span>
          <a-select
            placeholder="请选择平台"
            allow-clear
            class="input_self"
            v-model:value="state.platform"
            :options="state.platformList"
            style="width: 140px"
            />
            <!-- :options="state.folderList" -->
        </div>


        <a-button
          type="primary"
          :loading="state.serchLoding"
          @click="getMediaList"
          >查询</a-button
        >
        <a-button :loading="state.serchLoding" @click="resetSerch"
          >重置</a-button
        >
      </div>
    </div>

    <a-row justify="space-between" align="middle" style="margin-top:20px">
      <a-col>
        <div class="title_box">
          <div class="memory">
            <a-row justify="space-between" align="middle">
              <a-col style="cursor: pointer; margin-right: 30px">
                <a-tooltip>
                  <template #title
                    >免费空间： {{ state.capacityToTalFormat }}
                  </template>
                  {{ state.capacityFormat }} / {{ state.capacityToTalFormat }}
                  <span :style="percent >= 100 ? 'color: red' : 'color: #666'">
                    (已使用: {{ (state.percent < 1 ? 1 : state.percent) + "%" }})
                  </span>
                </a-tooltip>
              </a-col>
              <a-space>
                <a-col style="cursor: pointer;color:red" @click="clearClick"
                  ><delete-outlined style="margin-right: 5px" />清理</a-col
                >
                <a-col style="color:#918c8c">|</a-col>
                <a-col
                  style="cursor: pointer;color:#2b7aff"
                  @click="addMater"
                  ><inbox-outlined style="margin-right: 5px" />扩容</a-col
                >
                <a-col style="color:#918c8c">|</a-col>
                <a-col style="cursor: pointer" @click="goDowloadCenter"
                  ><arrow-down-outlined class="qingli" />下载中心
                </a-col>
              </a-space>
            </a-row>
          </div>
        </div>
      </a-col>
      <a-col>
        <div class="serch_right">
          <a-button style="margin-right: 10px" @click="goTagManage"
            ><tag-outlined /> 标签管理</a-button
          >
          <a-button @click="goItemTag"><tags-outlined />项目标签列表</a-button>
        </div>
      </a-col>
    </a-row>
 
    <!-- 项目列表 和 素材列表 -->
    <template v-if="!state.showProjectTagList">
      <div class="content_box">
        <!-- <div class="list_item_box">
          <div class="list_item_content_box">
            <div v-for="item in state.showMore ? state.itemList
              : state.itemList.slice(0, 10)" :key="item.id" class="list_item_title" @click="changeFn(item.id)">
              <span :class="{ active_span: isSelectId == item.id }">{{ item.name }}</span>
            </div>
          </div>

          <div class="switchover" @click="state.showMore = !state.showMore">
            更多项目
            <cu-icon :type="state.showMore ? 'icon-fangxiangshang' : 'icon-fangxiangxia'" />
          </div>
        </div> -->

        <!-- 素材列表 -->

        <a-table
          style="margin-top: 20px"
          :columns="cart_columns"
          :data-source="state.materialList"
          :loading="state.serchLoding"
          :pagination="false"
          :row-selection="{
            selectedRowKeys: state.selectedRowKeys,
            onChange: onSelectChange,
          }"
          :scroll="{ x: 2000 }"
          rowKey="id"
        >
          <template #bodyCell="{ column, record }">
            <!-- 素材 -->
            <template v-if="column.dataIndex === 'material_url'">
              <div class="video_box">
                <div class="video_left" style="width: 192px; overflow: hidden; display: flex; justify-content: center;">
                  <EyeOutlined  class="toView" @click="itemClick(record)">
                  </EyeOutlined>

                  <img v-if="record.cover_url && record.cover_url !=='' " :src="record.cover_url" alt="">
                    

                  <img  v-else  :src="state.default_corver" alt="" style="width: 35%; height: 100%;  object-fit: cover; 
                            transform: scale(3.2); transform-origin: center;">
                  <!-- <video v-else :src="record.material_url"></video> -->

                </div>
                <div class="video_right">
                  <span class="video_name">{{ record.material_name }}</span>
                  <!-- <span class="video_id">{{ record.task_name }}</span> -->
                </div>
              </div>
            </template>
            <!-- 创作任务 -->
            <template v-if="column.dataIndex === 'task_name'">
              <a-tooltip placement="top">
                <template #title>
                  <span>ID：{{ record.task_id }}</span>
                </template>
                <p
                  style="
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2; /* 显示两行 */
                    overflow: hidden;
                    text-overflow: ellipsis;
                    max-width: 150px;
                  "
                >
                  {{ record.task_name }}
                </p>
              </a-tooltip>
            </template>

            <!-- 剪辑来源 -->
            <template v-if="column.dataIndex === 'clip_name'">
              <a-tooltip placement="top">
                <template #title>
                  <span>ID：{{ record.clip_id }}</span>
                </template>
                <p
                  style="
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2; /* 显示两行 */
                    overflow: hidden;
                    text-overflow: ellipsis;
                    max-width: 150px;
                  "
                >
                  {{ record.clip_name }}
                </p>
              </a-tooltip>
            </template>

            <template v-if="column.dataIndex === 'pingtai'">
              <!-- <template v-if="true"> -->
              <template v-if="record.relation.length">
                <div class="pintai_list">
                  <div
                    class="pintai_itme"
                    v-for="item in record.relation"
                    :key="item.key"
                  >
                    <a-tooltip placement="topLeft">
                      <template #title>
                        <span>{{ item.value }}</span>
                      </template>
                      <img :src="item.image" alt="" />
                    </a-tooltip>
                  </div>
                </div>
              </template>
              <template v-else>
                <span>未发布</span>
              </template>
            </template>
            <template v-if="column.dataIndex === 'edit'">
              <a-dropdown :placements="bottomRight">
                <template #overlay>
                  <a-menu style="margin-left: 20px">
                    <template
                      v-for="(account, index) in state.accountList"
                      :key="account.key"
                    >
                      <template
                        v-if="
                        account.key !== 'weixinshipinhao'  && record.relation.some((ele) => ele.key == account.key)
                        "
                      >
                        <a-menu-item :disabled="true">
                          <div class="account_item">
                            <img :src="account.image" alt="" /><span>{{
                              account.value
                            }}</span>
                          </div>
                        </a-menu-item>
                      </template>

                      <template v-else>
                        <a-menu-item>
                          <div
                            class="account_item"
                            @click="go_DY_item(account, record)"
                          >
                            <img :src="account.image" alt="" /><span>{{
                              account.value
                            }}</span>
                          </div>
                        </a-menu-item>
                      </template>
                    </template>
                  </a-menu>
                </template>
                <a-button type="link"
                  >发布
                  <!-- <DownOutlined /> -->
                </a-button>
              </a-dropdown>
              <a-button type="link" @click="downloadFille('item', record)"
                >下载</a-button
              >
              <a-button type="link" @click="addTag(record)">标签</a-button>
              <a-button type="link" @click="deleteClick(record)">删除</a-button>
            </template>
          </template>
        </a-table>
        <div class="control_btns" v-if="selectItems.length">
          <div class="all_choose">
            <a-checkbox
              :checked="isCheckedAll()"
              @change="checkedAllFn"
              style="margin-right: 10px"
            />
            全选
            <div class="all_choose_text">
              已选择 {{ selectItems.length }} 个视频
            </div>
          </div>
          <a-dropdown :placements="bottomRight">
            <template #overlay>
              <a-menu style="margin-left: 80px">
                <a-menu-item
                  :key="account.key"
                  v-for="(account, index) in state.accountList"
                  :disabled="
                   account.key !== 'weixinshipinhao' && mergedResonArray.some((ele) => ele.key == account.key)
                  "
                >
                  <div
                    class="account_item"
                    @click="
                    account.key !== 'weixinshipinhao' &&  mergedResonArray?.some((ele) =>  ele.key == account.key)
                        ? () => {}
                        : handleMenuClick(account)
                    "
                  >
                    <img :src="account.image" alt="" /><span>{{
                      account.value
                    }}</span>
                  </div>
                </a-menu-item>
              </a-menu>
            </template>
            <a-button :disabled="!selectItems.length" type="primary"
              >发布至平台
              <DownOutlined />
            </a-button>
          </a-dropdown>
          <a-button
            :disabled="!selectItems.length"
            @click="downloadFille('items')"
            >下载</a-button
          >
          <a-button :disabled="!selectItems.length" danger @click="deleteItems"
            >删除</a-button
          >
        </div>
        <!-- 底部的 分页和发布 -->
        <div class="bottom_box">
          <!-- 分页器 -->
          <div style="display: flex">
            <div class="page-total">共 {{ state.total }} 条</div>
            <a-pagination
              :total="state.total"
              :current="state.page"
              :pageSize="state.pageSize"
              showSizeChanger="true"
              @change="PageChange"
            />
          </div>
        </div>
      </div>
    </template>

    <!-- 项目标签列表 -->
    <template v-else>
      <div class="scroll_con" style="overflow-y: scroll; height: 800px">
        <ProjectTagList
          :merchant_library_id="isSelectId"
          :group_id="isSelectId"
          :multimedia_id="state.multimedia_id"
          :projectName="isSelectItem?.name || ''"
          @back="
            () => {
              state.showProjectTagList = false;
            }
          "
        />
      </div>
    </template>
  </div>

  <!-- 详情弹框 -->
  <FileDetailModal
    :visible="state.visibleFileDetai"
    :data="viewItem"
    :index="state.fileIndex"
    @addTagChange="addTag"
    @onClose="fileDetailClose"
    @onSubmitMedia="fileDetailClose"
    :isPublish="state.isPublish"
    :openType="'chengPianPublish'"
  />

  <!-- 清理内存 -->
  <CleaningModal
    :visible="visibleCleaning"
    @onCancel="visibleCleaning = false"
    @onSubmit="onSubmitClean"
  />

  <!-- 添加标签弹窗 -->
  <tagsModal
    :visible="state.tagVisible"
    :labelInfo="viewItem"
    @close="
      () => {
        state.tagVisible = false;
        getMediaList();
      }
    "
  />

  <!-- 导出弹框 -->
  <ExportMdal
    :visible="state.visibleExport"
    @cacel="state.visibleExport = false"
  />


  <!-- 消耗提示组件 -->
  <NoticeFilm ref="NoticeFilmRef" @handleOk="isSubmit"> </NoticeFilm>

    <kuarong
    :capacityToTalFormat="state.capacityToTalFormat" 
    ref="kuarongRef"
  ></kuarong>

    <!-- 充值弹窗 -->
    <vipModal :visible="vipVisible" @close="vipVisible = false"></vipModal>

</template>

<script setup>
import { reactive, onMounted, watch, ref, nextTick, createVNode,onUnmounted } from "vue";
import request from "@/common/utils/request";
import { computed } from "vue";
import { useRouter } from "vue-router";
import kuarong from "@/views/shotstack/MaterialCenter/modules/kuarong.vue";

const router = useRouter();
const kuarongRef = ref(null);


import { saveAs } from "file-saver";

import { convertToDateOnly } from "@/views/shotstack/MuseMixedCut/utools";

// 消耗提示弹窗
import NoticeFilm from "@/views/shotstack/MaterialCenter/modules/NoticeFilm.vue";

import {
  SearchOutlined,
  DeleteOutlined,
  EllipsisOutlined,
  ExclamationCircleOutlined,
  EyeOutlined,
  ArrowDownOutlined,
  DownOutlined,
  InboxOutlined
} from "@ant-design/icons-vue";
import store from "@/store/index.js";

// 组件
// 项目标签列表
import ProjectTagList from "@/views/shotstack/tagManage/components/ProjectTagList/index.vue";

import tagsModal from "@/views/shotstack/MaterialCenter/modules/tagsModal.vue";

import ExportMdal from "@/views/shotstack/components/ExportMdal/index.vue";

import { message, Modal, Empty, notification } from "ant-design-vue";
import utils from'@/common/utils/utils.js'

// 查看素材详情列
import FileDetailModal from "@/views/shotstack/MaterialCenter/modules/FileDetailModal.vue";

import CleaningModal from "@/views/shotstack/MaterialCenter/modules/CleaningModal.vue";

// table 模板数据
import { cart_columns } from "./modules/index.js";
// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'
const vipModalRef = ref(null)
const vipVisible = ref(false)
// 视频预览组件
// import viewVideo from '@/views/shotstack/components/dialogComponent/viewVideo.vue'
// const viewVideoRef = ref(null)

// import MaterialList from "./MaterialList.vue";

const props = defineProps({
  isshowone: {
    type: Boolean,
    default: false,
  },
});

const state = reactive({
  default_corver:  utils.staticPath + "images/workAi/shotstack/default_corver.png",
  activeKey: "1",

  showMore: false, // 项目是否展示更多
  // 已使用空间
  capacityFormat: "",
  // 免费空间
  capacityToTalFormat: "",
  // 已使用空间百分比
  percent: 0,
  // 搜索成片
  material_name: "",
  // 头部项目列表
  itemList: [],
  // 素材列表
  materialList: [],
  // 当前选择的成片项目
  selectId: 0,
  // 是否显示项目标签列表
  showProjectTagList: false,
  // 下载素材弹窗
  visibleExport: false,
  // --
  multimedia_id: "",
  // 查看详情弹窗展示
  visibleFileDetai: false,
  // 添加标签弹窗展示
  tagVisible: false,

  // 查看详情弹窗索引
  fileIndex: 0,
  // 数据总数
  total: 0,
  // 分页器
  page: 1,
  pageSize: 10,
  // 开始结束时间
  time: ["", ""],
  // 搜索用的开始和结束时间
  start_time: "",
  end_time: "",
  // 选择的项目id
  merchant_library_id: null,
  // 文件夹id
  folder_id: null,
  // 文件夹列表
  folderList: [],
  // 搜索按钮loding
  serchLoding: false,
  // 当前预览的id
  viewItem_id: "",
  accountList: [],
  checkedAll: false,
  isPublish: false, //是否是查看发布平台详情
  // table 勾选的项
  selectedRowKeys: [],

  // 发布平台 搜索框列表
  platformList:[],
  // 发布平台搜索条件
  platform: null,

  // 发布状态 是否使用
  useRelease:'all'
  
});

onMounted(() => {
  if(store.getters.pageData?.CreateFilm?.page){
    nextTick(()=>{
      state.page = store.getters.pageData.CreateFilm.page
      state.pageSize = store.getters.pageData.CreateFilm.pageSize
    })
  }


  getItemList();
  getCapacity();
 
});

// 消耗提示组件
const NoticeFilmRef = ref(null);

const isCheckedAll = () => {
  const ids = state.materialList.map((item) => item.id);
  return ids.every((id) => state.selectedRowKeys.includes(id));
};

const checkbox_click = (index) => {
  state.materialList[index].checkedValue =
    !state.materialList[index].checkedValue;
  let allChecked = state.materialList.every((item) => item.checkedValue);
  state.checkedAll = allChecked;
};

// 默认返回成片第一个成片项目
// const isSelectId = computed({
//   get() {
//     return (typeof state.selectId == "number") ? state.selectId : state.itemList?.[0]?.id || "";
//   },
//   set(data) {
//     state.selectId = data;
//   },
// });

// 当前预览的项
const viewItem = computed(() => {
  return state.materialList.find((ele) => ele.id == state.viewItem_id);
});

// 返回当前选择的项目
// const isSelectItem = computed(() => {
//   return isSelectId.value
//     ? state.itemList.find((ele) => ele.id == isSelectId.value)
//     : {};
// });

const hasDyConfig = store?.state?.shotstack?.work_ai_config?.hasDyConfig || false;

// 获取剩余空间
const getCapacity = () => {
  request.get("/work_ai", "/user/shotstack/media/capacity").then((res) => {
    state.capacityFormat = res.capacityFormat;
    state.capacityToTalFormat = res.capacityToTalFormat;

    if (res.capacityToTalBytes >= 1) {
      state.percent = +(
        (Number(res.capacityBytes) / Number(res.capacityToTalBytes)) *
        100
      ).toFixed(1);
      return
    } 
    state.percent = 100
  });
};

// 分页change事件
const PageChange = (page, pageSize) => {
  state.page = page; //当前页码
  state.pageSize = pageSize; //当前页数
  store.dispatch('setPageData',{CreateFilm:{page,pageSize}})
  state.checkedAll = false;
  state.materialList.forEach((item) => {
    item.checkedValue = false;
  });

  getMediaList();
};

// 项目选择改变
const onSelectLibrary = (val) => {
  getMediaList();
  if (val) {
    getFolderList(val);
  } else {
    state.folderList = [];
    state.folder_id = null;
  }
};
const serchChange = (e) => {
  getMediaList();
};

// 获取项目列表
const getItemList = async () => {
  // debugger
  const res = await request.get(
    "/work_ai",
    "/user/shotstack/library/withGroup/list"
  );
  if (res && res.result.length) {
    state.itemList = res.result;
  } else {
    state.itemList = [];
  }
};

// 获取成片列表
const getMediaList = async () => {
  if(store.getters?.pageData?.CreateFilm?.page){
    state.page = store.getters.pageData.CreateFilm.page
    state.pageSize = store.getters.pageData.CreateFilm.pageSize
  }
  state.serchLoding = true;
  const params = {
    start_time: state.start_time,
    end_time: state.end_time,
    // 项目id
    merchant_library_id: state.merchant_library_id,
    // 当前展示的素材类型
    material_type: "video",
    page: state.page,
    pageSize: state.pageSize,
    // 搜索名称
    material_name: state.material_name,
    // 文件夹
    folder_id: state.folder_id,
    // 发布平台
    platform: (state.useRelease == 1 || state.useRelease == 2) ? state.platform : null,
    // 是否使用
    useRelease: state.useRelease == 'all' ? '' : state.useRelease
  };
  try {
    const res = await request.get(
      "/work_ai",
      "/user/shotstack/medias/video/list",
      params
    );
    console.log(res, "成片库媒体列表");
    res.result.data.forEach((ele) => {
      !ele.material_type &&
        (ele.material_type = ele?.folder?.folder_type || "");
    });
    state.materialList = res.result.data;
    state.total = res.result.total;
    state.serchLoding = false;
  } catch (error) {
    state.serchLoding = false;
    console.log(error);
  }
};

// 侦听项目的id, 发送请求
// watch(
//   () => isSelectId.value,
//   (nv) => {
//     state.page = 1;
//     state.pageSize = 10;
//     (typeof nv == "number") && getMediaList();
//   },
//   {
//     immediate: true
//   }
// );

const changeFn = (id) => {
  isSelectId.value = id;
};

const imageLoaded = (item) => {
  item.spinning = false;
};

// 选择日期发生变化
const timeChange = (value, model) => {
  console.log(model, "model");
  state.start_time = model[0];
  state.end_time = model[1];
  // // 日期被设为空值, 重新获取列表数据
  model[0] == "" && model[1] == "" && getMediaList();
};

// 去标签管理页
const goTagManage = () => {
  if (store.getters.isVersionExpired) {
    notification.warn({ message: "您的套餐已到期", duration: 2 });
   vipVisible.value = true
  } else {
    router.push({
      name: "TagManage",
      query: { id: "1" },
    });
  }
};

// 去 项目标签列表
const goItemTag = () => {
  if (store.getters.isVersionExpired) {
    notification.warn({ message: "您的套餐已到期", duration: 2 });
    vipVisible.value = true

  } else {
    router.push({
      name: "ItemTag",
      query: { id: "1" },
    });
  }
};
// 去下载中心
const goDowloadCenter = () => {
  router.push({
    name: "Download",
  });
};
// 素材卡片点击
const itemClick = (item, index) => {
  if (item.material_type == "text") {
    previewImg(item);
    return;
  }
  console.log(item, "选择的item");
  // 预览项的id
  state.viewItem_id = item.id;
  state.fileData = item;
  state.fileIndex = index;
  state.visibleFileDetai = true;
};

// 添加标签
const addTag = (item, index) => {
  // state.labelInfo = item;
  // state.labelInfo.index = index;
  state.viewItem_id = item.id;
  state.fileData = item;
  state.fileIndex = index;
  state.tagVisible = true;
};

// 旧的名称
const oldName = ref("");
// 修改名称
const inputRefs = ref([]);
const editNameInput = (item, index) => {
  oldName.value = item.material_name;
  item.isInput = true;
  nextTick(() => {
    console.log(inputRefs.value, "所有的input");
    inputRefs.value[index].focus();
  });
};

// 修改名称取消
const cancelEdit = (item) => {
  item.material_name = oldName.value;
  item.isInput = false;
};

// 确定修改名称
const submitEdit = (item) => {
  if (!item.material_name.trim()) {
    message.warn("请输入名称");
    return;
  }
  if (item.material_name.length > 20) {
    message.error("素材名称不能超过20个字符");
    return;
  }
  let params = {
    id: item.id,
    material_name: item.material_name,
  };
  request.put("/work_ai", "/user/shotstack/media/name", params).then((res) => {
    message.success("修改成功");
    item.isInput = false;
    // emit("changeSuccess");
  });
};

// 当前勾选的素材
const selectItems = computed(() => {
  // return state.materialList.filter((item) => item.checkedValue);
  return state.materialList.filter((item) =>
    state.selectedRowKeys.includes(item.id)
  );
});

// 下载素材
const downloadFille = (type, data) => {
  let ids = [];
  if (type == "items") {
    ids = selectItems.value.map((ele) => ele.id);
  } else {
    ids = [data.id];
  }
  request
    .put("/work_ai", "/user/shotstack/media/download", {
      ids,
    })
    .then((res) => {
      state.visibleExport = true;
    });
};

// 单个素材发布至抖音
const go_DY_item = (account, record) => {
  if (account?.developing == 1) {
    return message.warning("功能开发中");
  }
  if (account.key == "douyin" && hasDyConfig) {
    NoticeFilmRef.value.showModal(account.key, record);
  } else {
      router.push({
        name: "AutoRelease",
        query: {
        platform: account.key,
        choose: "1",
        id: record.id,
        material_type: record.material_type,
        },
      });
  }
};

// 删除 某项
const deleteClick = (item) => {
  Modal.confirm({
    title: `确定删除 ${item.material_name} 么？`,
    icon: createVNode(ExclamationCircleOutlined),
    cancelText: "取消",
    okText: "确定",
    onOk() {
      request
        .del("/work_ai", "/user/shotstack/media", {
          mediaIds: [item.id],
        })
        .then((res) => {
          // state.groupItem = {};
          message.success("删除成功");
          getMediaList();
        });
    },
  });
};

// 批量删除
const deleteItems = () => {
  Modal.confirm({
    title: `确定删除这些素材吗？`,
    icon: createVNode(ExclamationCircleOutlined),
    cancelText: "取消",
    okText: "确定",
    onOk() {
      request
        .del("/work_ai", "/user/shotstack/media", {
          mediaIds: selectItems.value.map((item) => item.id),
        })
        .then((res) => {
          // state.groupItem = {};
          message.success("删除成功");
          getMediaList();
        });
    },
  });
};

// 清空筛选数据
const resetData = () => {
  state.start_time = "";
  state.end_time = "";
  state.time = [];
  state.page = 1;
  state.pageSize = 10;
  state.merchant_library_id = null;
  state.folder_id = null;
  state.material_name = "";
  state.useRelease = 'all'
  state.platform = null
};

watch(
  () => props.isshowone,
  (nv) => {
    if (nv) {
      resetData();
      getMediaList();
    }
  },
  {
    immediate: true,
  }
);

const checkedAllFn = () => {
  state.checkedAll = !state.checkedAll;
  if (state.checkedAll == true) {
    state.selectedRowKeys = state.materialList.map((i) => i.id);
  } else {
    state.selectedRowKeys = [];
  }
};

// 获取发布成片平台下拉列表
const getAccountList = () => {
  request
    .get("/work_ai", "/org/platform/account/shotStackList", {
      filterShow: 1, //是否过滤掉没有对接的平台 1-是 0-不是
    })
    .then((res) => {
      state.accountList = res.result;
      
      state.platformList = res.result.map(ele => {
        return {
          label: ele.value,
          value: ele.key
        }
      })
      console.log(state.platformList,'res.result发发布平台');
    });
};
getAccountList();

// 获取成片文件夹列表
const getFolderList = async (merchant_library_id) => {
  // debugger
  const find = state.itemList.find((item) => item.id == merchant_library_id);
  const params = {
    folder_use_type: 2,
    material_type: "video",
    merchant_library_id,
    group_id: find.default_group_id,
  };
  const res = await request.post(
    "/work_ai",
    "/user/shotstack/folder/list",
    params
  );
  console.log(res.result, "文佳佳");
  if (res.result.data.length) {
    state.folderList = res.result.data.map((item) => {
      return {
        label: item.folder_name,
        value: item.id,
      };
    });
  }
};

// 跳转页面  / 判断
const handleMenuClick = (e) => {

  if (e?.developing == 1) {
    return message.warning("功能开发中");
  }
  if (e.key == "douyin" && hasDyConfig) {
    let choose ='2'
    NoticeFilmRef.value.showModal(e.key, choose );
  } else {
    let ids = state.selectedRowKeys;
    ids.length &&
      router.push({
        name: "AutoRelease",
        query: {
          platform: e.key,
          choose: "2",
          ids,
        },
      });
  }
};

const isSubmit = (e, type, ee_info) => {
  if (ee_info == '2') {
     let ids = state.selectedRowKeys;
     router.push({
        name: "AutoRelease",
        query: {
          platform: e,
          choose: "2",
          ids,
          type: type,
        },
      });
  } else {
     router.push({
        name: "AutoRelease",
        query: {
        choose: "1",
        id: ee_info.id,
        material_type: ee_info.material_type,
        type: type,
        platform: e,
        },
      });
  }

    
};

// 清理内存 弹窗
const visibleCleaning = ref(false);
// 清理内存
const clearClick = () => {
  visibleCleaning.value = true;
};

// 关闭内存弹窗
const onSubmitClean = () => {
  visibleCleaning.value = false;
  getCapacity();
};
// 查看详情组件关闭回调
const fileDetailClose = () => {
  state.isPublish = false;
  state.visibleFileDetai = false;
};
// 查看发布平台
const publishDetailHandle = (item, index) => {
  state.isPublish = true;
  itemClick(item, index);
};
const mergedResonArray = computed(() => {
  if (selectItems.value.length > 0) {
    return selectItems.value.reduce((acc, obj) => {
      return acc.concat(obj.relation);
    }, []);
  }
});

// table 勾选函数
const onSelectChange = (selectedRowKeys) => {
  console.log("selectedRowKeys changed: ", selectedRowKeys);
  state.selectedRowKeys = selectedRowKeys;
};

// 扩容
const addMater = () => {
  kuarongRef.value.showModal();
};

const resetSerch = () => {
  resetData();
  getMediaList();
};
</script>

<style lang="less" scoped>
@interval: 20px;

.ComposeMaterial {
  padding: 0 @interval;
  padding-left: 0;

  // min-width: 1510px;

  // 底部的按钮
  .bottom_box {
    margin-top: 20px;
    display: flex;
    align-content: center;
    justify-content: flex-end;
    padding-bottom: 30px;
  }
  .control_btns {
    position: fixed;
    bottom: 0;
    display: flex;
    gap: 8px;
    transition: opacity 0.4s;
    background-color: #fff;
    align-items: center;
    padding: 20px;
    box-shadow: 0px 12px 16px rgba(0, 0, 0, 0.12),
      0px 6px 8px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
  }
  // 最头部标题和剩余空间
  .title_box {
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  // 第二层 搜索容器
  .serch_title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20px;
    margin-top: 10px;

    .serch_left {
      display: flex;
      gap: 0 10px;

      .serch_item {
        display: flex;
        justify-content: center;
        align-items: center;

        .left_prefix {
          padding: 0 10px;
          background-color: #ffffff;
          line-height: 30px;
          border: 1px solid #d9d9d9;
          border-right: none;
        }
      }
    }
  }


  // 主要的项目列表和素材列表
  .content_box {
    // 头部项目选择列表
    .list_item_box {
      margin: 25px 0;
      display: flex;
      justify-content: space-between;

      .list_item_content_box {
        flex: 1;
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .list_item_title {
          padding: 2px 0;
          margin-right: 20px;
          cursor: pointer;
          white-space: nowrap;
          /* 强制文本在一行内显示 */
          overflow: hidden;
          /* 超出部分隐藏 */
          text-overflow: ellipsis;
          /* 超出部分显示省略号 */
          max-width: 21ch;

          /* 限制文本显示的最大字符数为10 */
          span {
            font-size: 15px;
            color: #aaaaaa;

            &.active_span {
              color: #222222;
              font-weight: 600;
            }

            &:hover {
              color: #222222;
              font-weight: 600;
            }
          }
        }
      }

      .switchover {
        min-width: 71px;
        padding: 5px 25px;
        cursor: pointer;
        display: flex;
        align-items: start;
      }
    }

    // table样式
    .video_box {
      display: flex;
      gap: 5px;

      .video_left {
        position: relative;
        // background-color: #000;

        // 预览小眼睛
        .toView {
          position: absolute;
          top: 35%;
          left: 50%;
          z-index: 9;
          opacity: 0;
          transition: all 0.3s;
          font-size: 25px;
          color: #fff;
          transform: translate(-50%);
          cursor: pointer;

          &:hover {
            color: rgb(0, 140, 255);
          }
        }

        &::after {
          content: "";
          position: absolute;
          left: 0;
          top: 0;
          z-index: 1;
          width: 90px;
          height: 90px;
          background: transparent;
          cursor: pointer;
          transition: all 0.3s;
        }

        &:hover {
          &::after {
            // background: rgba(0, 0, 0, 0.5);
          }

          .toView {
            opacity: 1;
          }
        }

        video {
          height: 90px;
          width: 90px;
        }

        img {
          width: 90px;
          height: 90px;
          aspect-ratio: auto;
        }
      }

      .video_right {
        display: flex;
        flex-direction: column;
        justify-content: center;

        .video_name {
          font-weight: 600;
          font-size: 15px;
          width: 120px;
          word-break: break-all;
          overflow-wrap: break-word;
        }

        .video_id {
          color: #525252;
          font-size: 14px;
        }
      }
    }

    .pintai_list {
      display: flex;
      gap: 10px;

      .pintai_itme {
        cursor: pointer;

        img {
          height: 30px;
          object-fit: contain;
        }
      }
    }
  }
}

.icon_eye {
  font-size: 18px;
  margin-right: 8px;
  color: #fff;
}

// 发布成片下拉样式
.account_item {
  width: 100px;
  height: 30px;
  display: flex;
  align-items: center;
  padding: 3px, 10px;
  position: relative;

  img {
    margin-right: 5px;
    width: 20px;
    height: 20px;
  }
}

.all_choose {
  display: flex;
  align-items: center;
  margin-right: 5px;

  .all_choose_text {
    margin-left: 10px;
    font-size: 14px;
    color: #989898;
    padding-right: 20px;
    border-right: 1px solid #989898;
  }
}

.page-total {
  margin: 5px 10px 0 0;
  font-size: 15px;
  color: #333;
}
</style>
